<template>
    <div class="role-menu-management">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>角色菜单权限管理</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>角色列表</span>
                </div>
              </template>
              <el-table
                :data="roleList"
                highlight-current-row
                @current-change="handleRoleChange"
              >
                <el-table-column prop="roleName" label="角色名称" />
                <el-table-column label="操作" width="100">
                  <template #default="{row}">
                    <el-button type="text" @click="handleSelectRole(row)">选择</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
          
          <el-col :span="16">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>菜单权限分配 - {{ currentRole?.roleName || '请选择角色' }}</span>
                  <el-button 
                    type="primary" 
                    :disabled="!currentRole"
                    @click="handleSavePermission"
                  >
                    保存权限
                  </el-button>
                </div>
              </template>
              
              <el-tree
                ref="menuTree"
                :data="menuTreeData"
                show-checkbox
                node-key="id"
                :props="treeProps"
                :default-checked-keys="checkedMenuKeys"
                :default-expand-all="true"
                check-strictly
              />
            </el-card>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted,nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import { getMenuTree } from '@/api/menu'
  import { getRoleList, getMenuIdsByRoleId, updateRoleMenus } from '@/api/role'
  
  interface Role {
    id: number
    roleName: string
  }
  
  interface Menu {
    id: number
    menuName: string
    children?: Menu[]
  }
  
  const roleList = ref<Role[]>([])
  const menuTreeData = ref<Menu[]>([])
  const currentRole = ref<Role | null>(null)
  const checkedMenuKeys = ref<number[]>([])
  const menuTree = ref()
  
  const treeProps = {
    children: 'children',
    label: 'menuName'
  }
  
  // 获取角色列表
  const fetchRoleList = async () => {
    try {
      const res = await getRoleList()
      roleList.value = res.data
    } catch (error) {
      ElMessage.error('获取角色列表失败')
    }
  }
  
  // 获取菜单树
  const fetchMenuTree = async () => {
    try {
      const res = await getMenuTree()
      menuTreeData.value = res.data
    } catch (error) {
      ElMessage.error('获取菜单数据失败')
    }
  }
  
  // 获取角色菜单权限
  const fetchRoleMenus = async (roleId: number) => {
    try {
      const res = await getMenuIdsByRoleId(roleId)
      checkedMenuKeys.value = res.data
      // 设置选中的菜单
      nextTick(() => {
        console.log(checkedMenuKeys.value)
        if(checkedMenuKeys.value!== null)
        menuTree.value?.setCheckedKeys(checkedMenuKeys.value)
        else menuTree.value?.setCheckedKeys([])
      })
    } catch (error) {
      ElMessage.error('获取角色权限失败')
    }
  }
  
  // 角色选择变化
  const handleRoleChange = (role: Role) => {
    currentRole.value = role
    if (role) {
      fetchRoleMenus(role.id)
    }
  }
  
  // 手动选择角色
  const handleSelectRole = (role: Role) => {
    currentRole.value = role
    fetchRoleMenus(role.id)
  }
  
  // 保存权限
  const handleSavePermission = async () => {
    if (!currentRole.value) return
    
    try {
      const checkedKeys = menuTree.value?.getCheckedKeys() || []
      const halfCheckedKeys = menuTree.value?.getHalfCheckedKeys() || []
      const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]
      
      await updateRoleMenus(currentRole.value.id, allCheckedKeys)
      ElMessage.success('权限保存成功')
    } catch (error) {
      ElMessage.error('保存权限失败')
    }
  }
  
  onMounted(() => {
    fetchRoleList()
    fetchMenuTree()
  })
  </script>
  
  <style scoped>
  .role-menu-management {
    padding: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  </style>